import re

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import authenticate
from itsdangerous import BadSignature

from apps.users.models import User


class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
    # username 有可能是手机号 也有可能是 用户名
    # 如果 username 满足 手机号的规则,我们就认为它手机号登陆
        try:
            if re.match(r'1[3-9]\d{9}',username):
                user = User.objects.get(mobile = username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        # 判断密码和user是否是认证用户
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from meiduo_mall import settings

# 给ID加密
def generate_verify_email_url(user_id):

    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    data = {'id': user_id}
    token = s.dumps(data).decode()

    verify_url = 'http://www.meiduo.site:8000/email_active/?token=' + token

    return verify_url

# 解密
def check_verify_url(token):

    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)

    try:
        result = s.loads(token)
    except BadSignature:
        return None

    return result.get('id')